﻿using System;
using System.Windows.Forms;
using Osm.Map.Layers.Tiles;
using Tools.Math.Geo;
using Osm.Map;
using Demo.TspDemo.ServiceSSVG;
using Net_Trading;
using Osm.Map.Layers.Custom;
using System.Collections.Generic;
using System.Diagnostics;
using DevExpress.XtraGrid.Views.Grid;
using System.Threading;
namespace Demo.TspDemo
{
    public partial class fen_main : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        System.Windows.Forms.Timer tmr = new System.Windows.Forms.Timer();
        System.Windows.Forms.Timer tmr2 = new System.Windows.Forms.Timer();
        private List<GeoCoordinate> _points;
        private CustomLayer _points_layer;
        private List<Thread> _threads ;
        private Thread tr;
        private Thread tr1;
        private Thread tr2;
        private delegate void EmptyDelegate();
        public fen_main()
        {
            InitializeComponent();
        }
        private void RefreshMap()
        {
            Singleton s = Singleton.Instance;
            var pos = s.Lesposition;
            _points = new List<GeoCoordinate>();
            _points_layer = new CustomLayer();
            _points.Clear();
            _points_layer.Clear();
            if (pos!=null)
            {
                for (int i = 0; i < pos.Count; i++)
                {  
                    _points_layer.AddImage(global::Demo.TspDemo.Properties.Resources.bluepin, pos[i]);
                    _points.Add(pos[i]);  
                }
                map_supervision.Map.Layers.Add(_points_layer);
                map_supervision.Refresh();
                map_supervision.Map.Layers.RemoveAt(1);  
            }  
        }
        void tmr_Tick(object sender, EventArgs e)
        {
            Invoke(new EmptyDelegate(RefreshMap));
        }
        void tmr2_Tick(object sender, EventArgs e)
        {
          //  Invoke(new EmptyDelegate(GetPositions));
          //  Invoke(new EmptyDelegate(RefreshMap));
        }
        public void VerifNotification()
        {
            while (true)
            {
                using (Service1 serv = new Service1())
                {
                    Singleton s = Singleton.Instance;
                    var p = serv.AfficherListeNoti();
                    
                    if (p.Length > s.NbNotif)
                    {
                        this.Invoke((MethodInvoker)delegate
                    {
                        alertControl1.Show(this, "Notification", p[p.Length - 1].Text);
                    });
                        s.NbNotif = p.Length;
                    }
                }
             //   MessageBox.Show("hi");
              //  barStaticItem4.Caption = "asba emchi";
            //    Thread.Sleep(5000);
            }


            
            //vrifier si le nombre total des notification a augmenter
            //si oui et l'etat de la dernière notification est non lu
            //alors on fait une notification

        }
     
        public void SetPositions()
        {
            while (true)
            {
                Singleton s = Singleton.Instance;
                var pos = s.Lesposition;
                 _points = new List<GeoCoordinate>();
                 _points_layer = new CustomLayer();
                if (s.Lesposition != null)
                {
                    for (int i = 0; i < pos.Count; i++)
                    {
                        _points.Add(pos[i]);
                        _points_layer.AddImage(global::Demo.TspDemo.Properties.Resources.bluepin, pos[i]);
                        
                    }
                    map_supervision.Map.Layers.Add(_points_layer);
                } 
            }

          
        
        }
        public void DelegateSetPosition()
        {
            Invoke(new EmptyDelegate(SetPositions));
        }
        public void DemarrerThreads()
        {
         //   for (int i = 0; i < 25; i++)
         //   {
            tr = new Thread(VerifNotification);
          //  tr1 = new Thread(DelegateGetPosition);
            tr2 = new Thread(DelegateSetPosition);
             //   Thread thread = new Thread(ThreadEntry);
            tr.IsBackground = true;
            tr1.IsBackground = true;
            tr2.IsBackground = true;
          //  thread.Name = string.Format("MyThread{0}", i);

            _threads.Add(tr);
            _threads.Add(tr1);
            _threads.Add(tr2);
           // while (true)
          //  {
                for (int i = 0; i < 3; i++)
                {
                    _threads[i].Start();
                }
        //    }

           // }
        }
        //void serv_RecupererPositionCompleted(object sender, RecupererPositionCompletedEventArgs e)
        //{
        //    Position[] p = e.Result;
        //    _points = new List<GeoCoordinate>();
        //    _points_layer = new CustomLayer();
        //    if (p != null)
        //    {
        //        for (int i = 0; i < p.Length; i++)
        //        {
        //            GeoCoordinate pt = new GeoCoordinate(p[i].Lat, p[i].Lon);
        //              this.Invoke((MethodInvoker)delegate
        //             {
        //                _points.Add(pt);
        //                _points_layer.AddImage(global::Demo.TspDemo.Properties.Resources.bluepin, pt);
        //                map_supervision.Map.Layers.Add(_points_layer);
        //                map_supervision.Refresh();
        //              });
        //        }
        //    }
        //}
        private void fen_main_Load(object sender, EventArgs e)
        {
            Singleton s = Singleton.Instance;
            barStaticItem2.Caption = String.Format("{0} {1}", s.Emp.Nom, s.Emp.Prenom);
            Service1 serv = new Service1();
            s.NbNotif = serv.AfficherListeNoti().Length;
            if (s.Emp.Type==0)
            {
                barStaticItem4.Caption = "Administrateur";
                
            }
            else
            {
                barStaticItem4.Caption = "Superviseur";
            }

            //Position[] p = serv.RecupererPosition();
            //_points = new List<GeoCoordinate>();
            //_points_layer = new CustomLayer();
            //if (p != null)
            //{
            //    for (int i = 0; i < p.Length; i++)
            //    {
            //        GeoCoordinate pt = new GeoCoordinate(p[i].Lat, p[i].Lon);
            //        _points.Add(pt);
            //        _points_layer.AddImage(global::Demo.TspDemo.Properties.Resources.bluepin, pt);
            //    }

            //}

                ribbonControl1.SelectedPage = ribbonPage1;
                WindowState = FormWindowState.Maximized;
                Map map = new Map();
                map.Layers.Add(new TilesLayer());
                map_supervision.Map = map;
                tmr.Interval = 100;
                tmr.Tick += new EventHandler(tmr_Tick);
                tmr.Enabled = true;
                tmr.Start();
                _threads = new List<Thread>();
                Worker c = new Worker();
              //  DemarrerThreads();
                tr = new Thread(VerifNotification);
                //tr1 = new Thread(DelegateGetPosition);
              //  tr2 = new Thread(DelegateSetPosition);
                tr.Start();
                
                //tr1.Start();
                
               // tr2.Start();
                
                //tmr2.Interval = 300;
                //tmr2.Tick += new EventHandler(tmr2_Tick);
                //tmr2.Enabled = true;
                //tmr2.Start();
          //  }
            //    map.Layers.Add(_points_layer);
                map_supervision.Center = new GeoCoordinate(35.84905, 9.821777);
                map_supervision.ZoomFactor = 8.16f;
                map_supervision.Refresh();
        }

        //private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    //refresh map 
        //    using (Service1 serv = new Service1())
        //    {
        //        Position[] p = serv.RecupererPosition();
        //        _points = new List<GeoCoordinate>();
        //        _points_layer = new CustomLayer();
        //        if (p != null)
        //        {
        //            for (int i = 0; i < p.Length; i++)
        //            {
        //                GeoCoordinate pt = new GeoCoordinate(p[i].Lat, p[i].Lon);
        //                _points.Add(pt);
        //                _points_layer.AddImage(global::Demo.TspDemo.Properties.Resources.bluepin, pt);
        //            }
        //        }
        //    }

        //    map_supervision.Refresh();
        //}

        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //global view 
            map_supervision.ZoomFactor = 5;
            map_supervision.Refresh();
            
        }
        private void allInvisible()
        {
            //fonction pour rendre tous les panels invisibles 
            panel_accueil.Visible = false;
            panel_chauffeur.Visible = false;
            panel_employer.Visible = false;
            panel_mission.Visible = false;
            panel_voiture.Visible = false;
        }

        private void ribbonControl1_SelectedPageChanged(object sender, EventArgs e)
        {
            Singleton s = Singleton.Instance;
            switch (ribbonControl1.SelectedPage.PageIndex)
            {

                case 0://accueil
                    {
                        allInvisible();
                        panel_accueil.Visible = true;
                        break;
                    }
                case 1://employer
                    {
                        allInvisible();
                        panel_employer.Visible = true;
                        s.Id = 0;
                        using (Service1 serv = new Service1())
                        {
                            gridControl1.DataSource= serv.AfficherListeEmployer();
                        }
                        
                        break;
                    }
                case 2://chauffeur
                    {
                        allInvisible();
                        panel_chauffeur.Visible = true;
                        s.Id = 0;
                        using (Service1 serv = new Service1())
                        {
                            gridControl2.DataSource = serv.AfficherListeChauffeur();
                        }
                        break;
                    }
                case 3://voiture
                    {
                        allInvisible();
                        panel_voiture.Visible = true;
                        s.Id = 0;
                        using (Service1 serv = new Service1())
                        {
                            gridControl3.DataSource = serv.AfficherListeVehicule();
                        }
                        break;
                    }

                case 4://mission
                    {
                        allInvisible();
                        panel_mission.Visible = true;
                        using (Service1 serv = new Service1())
                        {
                           schedulerStorage1.RefreshData();//= serv.AfficherListeVehicule();
                        }
                        break;
                    }
                case 5://message
                    {
                        Service1 serv=new Service1();
                        allInvisible();
                        panel_message.Visible = true;
                        gridControl4.DataSource = serv.AfficherListeMsg();
                        break;
                    }
            }
        }

        private void barButtonItem12_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //nouvelle mission
            fen_add_mission fm = new fen_add_mission();
            fm.Show();
        }

        private void barButtonItem13_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Application.Exit();
        }

        private void barButtonItem8_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //ajouter employer
            Singleton s = Singleton.Instance;
            fen_employer fe = new fen_employer();
            s.Modif=false;
            fe.Show();
        }

        private void gridControl1_MouseClick(object sender, MouseEventArgs e)
        {
            Singleton s = Singleton.Instance;
            s.Id = Convert.ToInt32(gridView1.GetFocusedRowCellDisplayText("id_employer"));
           // MessageBox.Show(c.ToString());
        }

        private void barButtonItem9_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //modifier employer
            Singleton s = Singleton.Instance;
            if (s.Id == 0)
            {
                MessageBox.Show("Veillez Selectionner un enregistrement !");
            }
            else
            { 
            fen_employer fe = new fen_employer();
            s.Modif = true;
            fe.Show();
            }
            
        }

        private void barButtonItem6_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //zoom out
            map_supervision.ZoomFactor = map_supervision.ZoomFactor-1;
            map_supervision.Refresh();
        }

        private void barButtonItem7_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //zoom in
            map_supervision.ZoomFactor = map_supervision.ZoomFactor+1;
            map_supervision.Refresh();
        }

        private void fen_main_Activated(object sender, EventArgs e)
        {
            //mise à jour des grid
            MAJData();
        }

        private void barButtonItem11_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //imprimer employer
            gridControl1.ShowPrintPreview();
        }

        private void barEditItem1_EditValueChanged(object sender, EventArgs e)
        {
            //rechercher employer
            gridView1.ApplyFindFilter(barEditItem1.EditValue.ToString());
        }

        private void barButtonItem14_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //export vers pdf employer
            GridView view = gridControl1.MainView as GridView;
            if (view != null)
            {
                view.ExportToPdf("employer.pdf");
                using (Process PdfExport = new Process())
                {
                    PdfExport.StartInfo.FileName = "AcroRd32.exe";
                    PdfExport.StartInfo.Arguments = "employer.pdf";
                    PdfExport.Start();
                }

            }
        }

        private void barButtonItem15_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //exporter vers xlsx employer
            GridView view = gridControl1.MainView as GridView;
            if (view != null)
            {
                view.ExportToXlsx("employer.xlsx");
                using (Process process = new Process())
                {
                    process.StartInfo.FileName = "employer.xlsx";
                    process.Start();
                    process.WaitForInputIdle();
                }

            }
        }

        private void barButtonItem16_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //exporter vers Html
            GridView view = gridControl1.MainView as GridView;
            if (view != null)
            {
                view.ExportToHtml("employer.html");
                using (Process process = new Process())
                {
                    process.StartInfo.FileName = "employer.html";
                    process.Start();
                    process.WaitForInputIdle();
                }

            }

        }

        private void fen_main_FormClosed(object sender, FormClosedEventArgs e)
        {
            tmr.Stop();
            tr.Abort();
            Application.Exit();
        }

        private void barButtonItem10_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //supprimer un employer
           var dr= MessageBox.Show("Voulez-Vous vraiment supprimer cet enregistrement?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

           if (dr==DialogResult.OK)
           {
               using (Service1 serv = new Service1())
               {
                   Singleton s = Singleton.Instance;
                   serv.SupprimerEmployer(s.Id);
               }
               MAJData();
           }
        }
        private void MAJData()
        {
            //mise à jour des grid
            using (Service1 serv = new Service1())
            {
                gridControl1.DataSource = serv.AfficherListeEmployer();
                gridControl2.DataSource = serv.AfficherListeChauffeur();
                gridControl3.DataSource = serv.AfficherListeVehicule();
            }
        }

        private void barButtonItem17_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //nouveau chauffeur
            Singleton s = Singleton.Instance;
            s.Modif = false;
            fen_chauffeur fc = new fen_chauffeur();
            fc.Show();

        }

        private void barButtonItem18_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //modifier chauffeur
            Singleton s = Singleton.Instance;
            if (s.Id == 0)
            {
                MessageBox.Show("Veillez Selectionner un enregistrement !");
            }
            else
            { 
            s.Modif = true;
            fen_chauffeur fc = new fen_chauffeur();
            fc.Show();
            }
            


        }

        private void gridControl2_MouseClick(object sender, MouseEventArgs e)
        {
            Singleton s = Singleton.Instance;
            s.Id = Convert.ToInt32(gridView2.GetFocusedRowCellDisplayText("id_chauffeur"));
        }

        private void barButtonItem20_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //imprimer chauffeur
            gridControl2.ShowPrintPreview();
        }

        private void barEditItem2_EditValueChanged(object sender, EventArgs e)
        {
            //rechercher chauffeur
            gridView2.ApplyFindFilter(barEditItem2.EditValue.ToString());
        }

        private void barButtonItem21_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //export vers pdf chauffeur
            GridView view = gridControl2.MainView as GridView;
            if (view != null)
            {
                view.ExportToPdf("chauffeur.pdf");
                using (Process PdfExport = new Process())
                {
                    PdfExport.StartInfo.FileName = "AcroRd32.exe";
                    PdfExport.StartInfo.Arguments = "chauffeur.pdf";
                    PdfExport.Start();
                }

            }
        }

        private void barButtonItem22_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //exporter vers xlsx chauffeur
            GridView view = gridControl2.MainView as GridView;
            if (view != null)
            {
                view.ExportToXlsx("chauffeur.xlsx");
                using (Process process = new Process())
                {
                    process.StartInfo.FileName = "chauffeur.xlsx";
                    process.Start();
                    process.WaitForInputIdle();
                }

            }
        }

        private void barButtonItem23_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //exporter vers Html
            GridView view = gridControl2.MainView as GridView;
            if (view != null)
            {
                view.ExportToHtml("chauffeur.html");
                using (Process process = new Process())
                {
                    process.StartInfo.FileName = "chauffeur.html";
                    process.Start();
                    process.WaitForInputIdle();
                }

            }
        }

        private void barButtonItem5_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            using (Service1 serv = new Service1())
            {
                Position[] p = serv.RecupererPosition();
                _points = new List<GeoCoordinate>();
                _points_layer = new CustomLayer();
                if (p != null)
                {
                    for (int i = 0; i < p.Length; i++)
                    {
                        GeoCoordinate pt = new GeoCoordinate(p[i].Lat, p[i].Lon);
                        _points.Add(pt);
                        _points_layer.AddImage(global::Demo.TspDemo.Properties.Resources.bluepin, pt);
                    }
                }
                map_supervision.Refresh();
            }
        }

    }
}
